package filefunc

import (
	"fmt"
	"github.com/gogf/gf/errors/gerror"
	flog "gitlab.local/DO-module/new-filemanage-module/src/service/log"
	"gitlab.local/golibrary/filedownload"
	"os"
	"time"
)

type DownloadLog struct {
	TaskId      string                 `json:"task_id"`      //任务id
	Name        string                 `json:"name"`         //名称
	Size        int64                  `json:"size"`         //总大小B(-1未知)
	Rate        float32                `json:"rate"`         //进度百分百
	Status      filedownload.RunStatus `json:"status"`       //运行状态,1.未运行，2.运行中，3.暂停，4.终止，5.完成，6.失败
	ToPath      string                 `json:"to_path"`      //保存文件
	CurrentSize int64                  `json:"current_size"` //当前已完成大小(B)
}

type AllBackgroundTaskLog struct {
	TaskId      string      `json:"task_id"`      //id
	Type        interface{} `json:"type"`         //类型
	Name        string      `json:"name"`         //名称
	Size        int64       `json:"size"`         //大小
	Rate        float32     `json:"rate"`         //进度
	Status      interface{} `json:"status"`       //状态
	ErrorMsg    string      `json:"error_msg"`    //错误信息
	FileTotal   int64       `json:"file_total"`   //文件总数量
	CurrentSize int64       `json:"current_size"` //当前已完成大小(B)
	ToPath      string      `json:"to_path"`      //目标文件夹路径
	TaskType    string      `json:"task_type"`    //任务类型
}

// newDownloadTask 创建新的远程下载任务
func (f *FileFunc) newDownloadTask(urlPath, outDir, uname string) error {
	task, err := filedownload.NewTask(urlPath, outDir, uname)
	if err != nil {
		return gerror.Wrap(err, "deliversRemoteDownloadTask")
	}
	task.RegisterEndFn(f.registerEndFn)

	q, b := f.remoteDownloadQueue[uname]
	if !b {
		q = &download{}
		f.remoteDownloadQueue[uname] = q
	}

	q.Lock()

	if f.remoteRunNum >= f.remoteLimitNum {
		//正在运行的任务数大于等于最大限制，将任务改成等待状态
		task.Status = filedownload.Waiting
	} else {
		f.remoteRunNum++
		err = task.Run()
	}

	q.queue = append(q.queue, task)

	q.Unlock()

	return err
}

func (f *FileFunc) registerEndFn(taskId, outFile, _, uname string, status filedownload.RunStatus, err error) {
	f.remoteRunNum--

	if f.remoteRunNum < f.remoteLimitNum {
		f.nextTask(uname)
	}

	// 删除已完成的任务
	if q, ok := f.remoteDownloadQueue[uname]; ok {
		go func() {
			time.Sleep(3 * time.Second)
			q.Lock()
			defer q.Unlock()
			for i, t := range q.queue {
				if t.TaskId == taskId {
					q.queue = append(q.queue[:i], q.queue[i+1:]...)
					break
				}
			}
		}()
	}

	switch status {
	case filedownload.Finish: //下载成功
		//继承父级acl权限
		/*_ = f.Acl.InheritedPermissions(outFile, "", false)*/
		flog.RecordedLog(flog.Err, uname, flog.HttpTag, fmt.Sprintf("remote download complete[%s]", taskId), "")
	case filedownload.Fail: //下载失败
		_ = os.Remove(outFile)
		flog.RecordedLog(flog.Err, uname, flog.HttpTag, fmt.Sprintf("remote download failure[%s]", err), "")
	}
}

func (f *FileFunc) nextTask(uname string) {
	q, b := f.remoteDownloadQueue[uname]
	if !b {
		return
	}

	q.Lock()

	for _, v := range q.queue {
		//执行等待中的任务
		if v.Status == filedownload.Waiting {
			f.remoteRunNum++
			if err := v.Run(); err != nil {
				flog.RecordedLog(flog.Err, v.Uname, flog.HttpTag, "remote download failure", "")
			}
			break
		}
	}

	q.Unlock()
}
